package com.smile.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射给对象赋值
 * 
 * @author panzhenxing
 *
 */
public class ReflectTool {
	/**
	 * 将实体类的null转换成默认值，string转为空字符串，Byte/Short/Integer/Long转为0
	 * 
	 * @param modelObject
	 */
	@SuppressWarnings("rawtypes")
	public static void convertNullToDefault(Object modelObject) {
		if (null != modelObject) {
			if (modelObject instanceof java.util.List) {
				for (Object model : (java.util.List) modelObject) {
					convertNullToDefaultModel(model);
				}
			} else {
				convertNullToDefaultModel(modelObject);
			}
		}

	}

	private static void convertNullToDefaultModel(Object model) {
		Field[] field = model.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
		try {
			for (int j = 0; j < field.length; j++) { // 遍历所有属性
				String name = field[j].getName(); // 获取属性的名字
				name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
				String type = field[j].getGenericType().toString(); // 获取属性的类型
				if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class
																	// "，后面跟类名
					Method m = model.getClass().getMethod("get" + name);
					String value = (String) m.invoke(model); // 调用getter方法获取属性值
					if (value == null) {
						m = model.getClass().getMethod("set" + name, String.class);
						m.invoke(model, "");
					}
				}
				if (type.equals("class java.lang.Integer")) {
					Method m = model.getClass().getMethod("get" + name);
					Integer value = (Integer) m.invoke(model);
					if (value == null) {
						m = model.getClass().getMethod("set" + name, Integer.class);
						m.invoke(model, new Integer(0));
					}
				}
				if (type.equals("class java.lang.Byte")) {
					Method m = model.getClass().getMethod("get" + name);
					Byte value = (Byte) m.invoke(model);
					if (value == null) {
						m = model.getClass().getMethod("set" + name, Byte.class);
						m.invoke(model, new Byte("0"));
					}
				}
				if (type.equals("class java.lang.Long")) {
					Method m = model.getClass().getMethod("get" + name);
					Long value = (Long) m.invoke(model);
					if (value == null) {
						m = model.getClass().getMethod("set" + name, Long.class);
						m.invoke(model, new Long(0));
					}
				}
				if (type.equals("class java.lang.Short")) {
					Method m = model.getClass().getMethod("get" + name);
					Long value = (Long) m.invoke(model);
					if (value == null) {
						m = model.getClass().getMethod("set" + name, Long.class);
						m.invoke(model, new Long(0));
					}
				}
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
